import numpy as np
from scipy import stats
import seaborn as sns
import numpy.random as npr
import matplotlib

matplotlib.use(backend="TkAgg")
import matplotlib.pyplot as plt

plt.rcParams['font.family'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False


# 演示不连续函数的积分
def discontinuous_function(x):
    """一个有多个不连续点的函数"""
    result = np.zeros_like(x)
    mask1 = (x >= -2) & (x < -1)
    mask2 = (x >= -1) & (x < 0)
    mask3 = (x >= 0) & (x < 1)
    mask4 = (x >= 1) & (x <= 2)

    result[mask1] = 0.1
    result[mask2] = 0.3
    result[mask3] = 0.2
    result[mask4] = 0.4

    return result


# 计算这个函数的积分（勒贝格积分思想）
x_disc = np.linspace(-2, 2, 1000)
f_disc = discontinuous_function(x_disc)

# 黎曼积分近似
dx = x_disc[1] - x_disc[0]
riemann_integral = np.sum(f_disc) * dx

# 勒贝格积分（通过测度计算）
intervals = [(-2, -1), (-1, 0), (0, 1), (1, 2)]
values = [0.1, 0.3, 0.2, 0.4]
lebesgue_integral = sum(val * (b - a) for (a, b), val in zip(intervals, values))

plt.figure(figsize=(12, 6))
plt.plot(x_disc, f_disc, 'b-', linewidth=2)
plt.xlabel('x')
plt.ylabel('f(x)')
plt.title('不连续函数的积分演示')
plt.grid(True, alpha=0.3)

# 标记不连续点
for point in [-1, 0, 1]:
    plt.axvline(x=point, color='r', linestyle='--', alpha=0.5)

plt.text(0.5, 0.35, f'黎曼积分近似: {riemann_integral:.6f}', fontsize=12)
plt.text(0.5, 0.3, f'勒贝格积分精确值: {lebesgue_integral:.6f}', fontsize=12)

plt.show()

print("不连续函数的积分:")
print(f"黎曼积分近似值: {riemann_integral:.6f}")
print(f"勒贝格积分精确值: {lebesgue_integral:.6f}")
print(f"在概率论中，即使密度函数不连续，勒贝格积分也能给出精确结果")